package com.itstu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.itstu.common.constant.AuthServerConstant;
import com.itstu.common.utils.HttpUtils;
import com.itstu.common.utils.R;
import com.itstu.gulimall.auth.feign.MemberFeignService;
import com.itstu.common.vo.MemberResponVo;
import com.itstu.gulimall.auth.vo.SocialUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 * @author shhjiang_001
 * @create 2020-05-28 16:52
 */
@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;
    @GetMapping("oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

        // 根据code换取accessToken
        Map<String, String> map = new HashMap<>();
        map.put("client_id","3821303060");
        map.put("client_secret","9f71c6399b5cb322ea9a975ff066de3b");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);

        HttpResponse post = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(),new HashMap<>(),map);
        // 处理
        if (post.getStatusLine().getStatusCode() == 200){
            String json = EntityUtils.toString(post.getEntity());
            SocialUserVo socialUserVo = JSON.parseObject(json, SocialUserVo.class);
            // 知道是哪个社交用户，是第一次还是？ 登录还是注册,调用远程服务
            R login = memberFeignService.oauth2Login(socialUserVo);
            if (login.getCode() == 0){
                // 登录成功就跳转回首页
                MemberResponVo data = login.getData("data", new TypeReference<MemberResponVo>() {
                });
                log.info("登录成功，用户信息：{}",data.getNickname());
                // 第一次
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                return "redirect:http://gulimall.com";
            }else{
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

}
